import { ref } from "vue";
import useTableConfigStore from "@/store/modules/tableConfig";
import { initTableConfig as initTable } from "@/api/system/role";
import { VxeGridPropTypes } from "../../types/index";
import { generateBaseFunc, addDateRange, jsonFormat } from "./common";
import { stringToBoolean } from "./common";
import XEUtils from "xe-utils";
import request from "@/utils/request";
import { HandConfig, VxeBasicTable } from "@/components/ElementRender/src/types";
import { titleCase } from "@/utils";
import { getUserTable } from "@/api/system/user";
import { RequestHttpEnum } from "@/enums/httpEnum";
import useBaseApi from "@/api/base/index";
/**
 * 初始表格配置信息
 */
export function initTableConfig(data: Object) {
    initTable(data).then((resp) => {
        useTableConfigStore().initTableConfig(resp?.data);
    });
}
/**
 * 获取表格配置数据
 */
export function useTableConfig(...args: any[]) {
    const res = ref<any>({});
    return new Promise<any>((resolve) => {
        args.forEach((item: any) => {
            res.value[item.key] = [];
            const table = useTableConfigStore().getTableConfig(item.key);
            if (table) {
                resolve(table);
            } else {
                const data = {
                    role: item.role,
                    tableName: item.tableName,
                };
                getUserTable(data)
                    .then((resp) => {
                        res.value[item.key] = resp.data;
                        useTableConfigStore().setTableConfig(item.key, res.value[item.key]);
                        resolve(resp.data);
                    })
                    .catch(() => {
                        resolve({});
                    });
            }
        });
    });
}
/**
 * 更新表格配置数据
 * @param args
 * @returns
 */
export function updateTableConfig(...args: any[]) {
    const res = ref<any>({});
    return new Promise<any>((resolve) => {
        args.forEach((item: any) => {
            res.value[item.key] = [];
            const data = {
                role: item.role,
                tableName: item.tableName,
            };
            getUserTable(data)
                .then((resp) => {
                    res.value[item.key] = resp.data;
                    useTableConfigStore().setTableConfig(item.key, res.value[item.key]);
                    resolve(resp.data);
                })
                .catch(() => {
                    resolve({});
                });
        });
    });
}

/**
 处理boolean类型及函数字符串
 * @param params
 */
export function booleanFunction(params: string | any) {
    if (!params) {
        return params;
    }
    const v = stringToBoolean(params);
    if (typeof v === "boolean") {
        return v;
    } else {
        const fun = generateBaseFunc(params);
        return fun;
    }
}
function requestMethod(url: string, method: string, data: any) {
    if (method == RequestHttpEnum.POST || method == RequestHttpEnum.PUT) {
        return request({
            url: url,
            method: method,
            data: data,
        });
    } else if (method == RequestHttpEnum.GET) {
        return request({
            url: url,
            method: method,
            params: data,
        });
    } else {
        return request({
            url: url,
            method: method,
            params: data,
        });
    }
}
/**
 * 数据代理配置
 * @param proxyConfig 代理配置
 * @param handConfig 操作配置
 * @param uniqueId 数据主键
 * @param formConfig 查询表单配置
 * @param pagerConfig 分页配置
 * @param params 额外的查询参数
 * @returns
 */
export function useProxyConfig(proxyConfig: VxeGridPropTypes.ProxyConfig, handConfig: HandConfig, uniqueId: string, formConfig: VxeGridPropTypes.FormConfig, pagerConfig: VxeGridPropTypes.PagerConfig, params: Array<object> = []): VxeGridPropTypes.ProxyConfig {
    const ajax = {
        query: async ({ page, sorts, filters, form }: VxeGridPropTypes.ProxyAjaxQueryParams, ...args: any) => {
            const queryParams: any = Object.assign({}, form, ...args, ...params);
            if (!XEUtils.isEmpty(pagerConfig) && pagerConfig.enabled) {
                Object.assign(queryParams, page);
            }
            // 时间范围处理

            if (formConfig && formConfig.enabled) {
                XEUtils.arrayEach(formConfig.items, (item: any) => {
                    if (queryParams[item.field]) {
                        if (item.itemRender && item.itemRender.name == "ElDatePicker") {
                            // 处理时间范围查询
                            Object.assign(queryParams, addDateRange({}, form[item.field], item.field));
                        }
                    }
                });
            }

            // 处理排序条件
            const orderByColumn = <Array<String>>[];
            const isAsc = <Array<Boolean>>[];
            sorts.forEach((m: any) => {
                orderByColumn.push(m.field);
                isAsc.push(m.order);
            });
            queryParams.orderByColumn = orderByColumn.join(",");
            queryParams.isAsc = isAsc.join(",");
            // 处理筛选条件
            filters.forEach(({ property, values }) => {
                queryParams[property] = values.join(",");
            });
            // 查询前处理，返回false时将不查询
            if (proxyConfig["query"]?.beforeQuery && typeof proxyConfig["query"]?.beforeQuery == "string") {
                const queryIntercept = await generateBaseFunc(proxyConfig["query"]?.beforeQuery)({
                    queryParams,
                    query: { page, sorts, filters, form, ...args },
                    config: { proxyConfig, handConfig, uniqueId, formConfig, params },
                });
                if (typeof queryIntercept == "boolean" && !queryIntercept) {
                    return;
                }
            }

            // return request({
            //     url: proxyConfig["query"]?.api,
            //     method: proxyConfig["query"].method,
            //     params: queryParams,
            // }).then((response) => {
            //     return { data: response, total: 1000 };
            // });
            return requestMethod(proxyConfig["query"]?.api, proxyConfig["query"].method, queryParams).then((response) => {
                return response;
            });
        },
        queryAll: async ({ page, sorts, filters, form }: any, ...args: any) => {
            const queryParams: any = Object.assign({}, form);
            // 查询前处理，返回false时不执行查询
            if (proxyConfig["queryAll"]?.beforeQueryAll && typeof proxyConfig["queryAll"]?.beforeQueryAll == "string") {
                const queryAllIntercept = await generateBaseFunc(proxyConfig["queryAll"]?.beforeQueryAll)({
                    queryParams,
                    query: { page, sorts, filters, form, ...args },
                    config: { proxyConfig, handConfig, uniqueId, formConfig, params },
                });
                if (typeof queryAllIntercept == "boolean" && !queryAllIntercept) {
                    return;
                }
            }
            // return await request({
            //     url: proxyConfig["queryAll"]?.api,
            //     method: "get",
            //     params: queryParams,
            // }).then(async (response) => {
            //     // 查询成功后面处理
            //     if (proxyConfig["queryAll"]?.afterQueryAll && typeof proxyConfig["queryAll"]?.afterQueryAll == "string") {
            //         await generateBaseFunc(proxyConfig["queryAll"]?.afterQueryAll)({
            //             queryParams,
            //             query: { page, sorts, filters, form, ...args },
            //             config: { proxyConfig, handConfig, uniqueId, formConfig, params },
            //             data: response,
            //         });
            //     }
            //     return response;
            // });
            return requestMethod(proxyConfig["queryAll"]?.api, proxyConfig["queryAll"].method, queryParams).then(async (response) => {
                // 查询成功后面处理
                if (proxyConfig["queryAll"]?.afterQueryAll && typeof proxyConfig["queryAll"]?.afterQueryAll == "string") {
                    await generateBaseFunc(proxyConfig["queryAll"]?.afterQueryAll)({
                        queryParams,
                        query: { page, sorts, filters, form, ...args },
                        config: { proxyConfig, handConfig, uniqueId, formConfig, params },
                        data: response,
                    });
                }
                return response;
            });
        },
    };
    if (handConfig) {
        //新增和修改数据代理
        if (handConfig["modify"] || handConfig["add"]) {
            ajax["save"] = async ({ body }: any, ...args: any) => {
                console.log("保存数据", body);
                let callBatchSave;
                if (handConfig["add"] && !proxyConfig["insert"]?.api) {
                    return new Promise((resolve, reject) => {
                        reject({ msg: "没有配置保存接口" });
                    });
                } else {
                    callBatchSave = (data: any) => {
                        // return request({
                        //     url: proxyConfig["insert"]?.api,
                        //     method: "post",
                        //     data,
                        // });
                        return requestMethod(proxyConfig["insert"]?.api, proxyConfig["insert"].method, data);
                    };
                }
                let callBatchModify;
                if (handConfig["modify"] && !proxyConfig["update"]?.api) {
                    return new Promise((resolve, reject) => {
                        reject({ msg: "没有配置修改接口" });
                    });
                } else {
                    callBatchModify = (data: any) => {
                        // return request({
                        //     url: proxyConfig["update"]?.api,
                        //     method: "put",
                        //     data,
                        // });
                        return requestMethod(proxyConfig["update"]?.api, proxyConfig["update"].method, data);
                    };
                }
                const insertFlag = ref(true);
                // 添加前处理函数
                if (proxyConfig["insert"]?.beforeInsert) {
                    const insertIntercept = await generateBaseFunc(proxyConfig["insert"]?.beforeInsert)({
                        body,
                        extra: { ...args },
                        config: { proxyConfig, handConfig, uniqueId, formConfig, params },
                    });
                    if (typeof insertIntercept == "boolean" && !insertIntercept) {
                        insertFlag.value = insertIntercept;
                    }
                }
                const updateFlag = ref(true);
                // 修改之前处理函数
                if (proxyConfig["update"]?.beforeUpdate) {
                    const updateIntercept = await generateBaseFunc(proxyConfig["update"]?.beforeUpdate)({
                        body,
                        extra: { ...args },
                        config: { proxyConfig, handConfig, uniqueId, formConfig, params },
                    });
                    if (typeof updateIntercept == "boolean" && !updateIntercept) {
                        updateFlag.value = updateIntercept;
                    }
                }
                if (body.updateRecords.length > 0 && body.insertRecords.length > 0) {
                    handConfig["modify"] && updateFlag.value ? await callBatchModify(body.updateRecords) : null;
                    handConfig["add"] && insertFlag.value ? await callBatchSave(body.insertRecords) : null;
                    return;
                }
                if (body.updateRecords.length > 0 && handConfig["modify"] && updateFlag.value) {
                    return await callBatchModify(body.updateRecords);
                }
                if (body.insertRecords.length > 0 && handConfig["add"] && insertFlag.value) {
                    return await callBatchSave(body.insertRecords);
                }
            };
        }
        //删除操作
        if (handConfig["remove"]) {
            ajax["delete"] = async ({ body }: any, ...args: any) => {
                console.log("删除", body);
                let callRemoves;
                if (handConfig["remove"] && !proxyConfig["delete"]?.api) {
                    return new Promise((resolve, reject) => {
                        reject({ msg: "没有配置删除接口" });
                    });
                } else {
                    callRemoves = (data: any) => {
                        // return request({
                        //     url: proxyConfig["delete"]?.api,
                        //     method: "delete",
                        //     data,
                        // });
                        return requestMethod(proxyConfig["delete"]?.api, proxyConfig["delete"].method, data);
                    };
                }
                // 删除前处理，返回false时不执行删除
                if (proxyConfig["delete"]?.beforeDelete && typeof proxyConfig["delete"]?.beforeDelete == "string") {
                    const deleteIntercept = await generateBaseFunc(proxyConfig["delete"]?.beforeDelete)({
                        body,
                        extra: { ...args },
                        config: { proxyConfig, handConfig, uniqueId, formConfig, params },
                    });
                    if (typeof deleteIntercept == "boolean" && !deleteIntercept) {
                        return;
                    }
                }
                return await callRemoves(body.removeRecords.map((item: any) => item[uniqueId]));
            };
        }
        return {
            paramsChangeLoad: proxyConfig["paramsChangeLoad"] ? proxyConfig["paramsChangeLoad"] : false,
            enabled: proxyConfig["enabled"] ? proxyConfig["enabled"] : true,
            autoLoad: proxyConfig["autoLoad"] ? proxyConfig["autoLoad"] : true,
            message: proxyConfig["message"] ? proxyConfig["message"] : true,
            seq: proxyConfig["seq"] ? proxyConfig["seq"] : false,
            sort: proxyConfig["sort"] ? proxyConfig["sort"] : false,
            filter: proxyConfig["filter"] ? proxyConfig["filter"] : false,
            form: proxyConfig["form"] ? proxyConfig["form"] : true,
            props: {
                list: proxyConfig["props"]["list"] ? proxyConfig["props"]["list"] : null,
                result: proxyConfig["props"]["result"] ? proxyConfig["props"]["result"] : "rows",
                total: proxyConfig["props"]["total"] ? proxyConfig["props"]["total"] : "total",
                message: proxyConfig["props"]["message"] ? proxyConfig["props"]["message"] : "message",
            },
            ajax: ajax,
            afterQuery: booleanFunction(proxyConfig["query"]?.afterQuery),
            afterDelete: booleanFunction(proxyConfig["delete"]?.afterDelete),
            afterSave: booleanFunction(proxyConfig["save"]?.afterSave),
        };
    } else {
        return {};
    }
}
/**
 * 表格列配置
 * @param columns
 * @returns
 */
export function useColumns(columns: VxeGridPropTypes.Columns) {
    const columnList = ref<Array<any>>([]);
    // 需要处理的列函数
    const defaultDisFun = ["className", "headerClassName", "footerClassName", "formatter", "sortBy", "filterMethod", "filterResetMethod", "filterRecoverMethod", "exportMethod", "footerExportMethod"];
    // 处理渲染器中的函数
    XEUtils.arrayEach(columns, (arrayItem: any) => {
        XEUtils.objectEach(arrayItem, (item, key) => {
            if (defaultDisFun.includes(key) && !XEUtils.isEmpty(item)) {
                arrayItem[key] = generateBaseFunc(item);
            }
        });
        arrayItem = jsonFormat(arrayItem);
        if (arrayItem?.editRender && arrayItem?.editRender?.defaultValue) {
            arrayItem.editRender.defaultValue = generateBaseFunc(arrayItem.editRender.defaultValue);
        }
        columnList.value.push(arrayItem);
    });
    return columnList.value.sort(function (prev: any, curr: any) {
        return prev.sortNo - curr.sortNo;
    });
}

// 工具栏配置
const { callGetOne, callModify } = useBaseApi("/print/printPanel");
const { callGetOne: callGetOnePro } = useBaseApi("/print/printProvider");
export function useToolBar(toolbarConfig: VxeGridPropTypes.ToolbarConfig, tableProps: any, $table: any) {
    // 打印时数据查询接口
    const queryBusinessData = (params: any) => {
        return request({
            url: toolbarConfig["printDataQueryPort"],
            method: "get",
            params,
        });
    };
    // 打印模板设计
    if (toolbarConfig?.printDesign?.setPrintTemplate) {
        const setApi = {
            // 拖拽面板查询接口
            queryProvider: () => {
                return callGetOnePro(toolbarConfig.printDesign?.setPrintTemplateConfig?.queryProvider).then((response: any) => {
                    return { data: JSON.parse(response.data?.providerData) };
                });
            },
            // 模板查询接口，返回模板数据
            queryPanel: () => {
                return callGetOne(toolbarConfig.printDesign?.setPrintTemplateConfig?.queryPanel).then((response: any) => {
                    return { data: JSON.parse(response.data?.panelData) };
                });
            },
            // 保存模板时调用接口
            saveDesign: async (data: any) => {
                return await callModify(data);
            },
        };
        toolbarConfig.printDesign.setPrintTemplateConfig = Object.assign({ ...toolbarConfig.printDesign?.setPrintTemplateConfig }, setApi);
    }
    // 打印预览
    if (toolbarConfig?.printDesign?.previewPrint) {
        const preview = {
            queryPanel: () => {
                return callGetOne(toolbarConfig.printDesign?.previewPrintConfig?.queryPanel).then((response: any) => {
                    return { data: JSON.parse(response.data?.panelData) };
                });
            },
            // 打印数据查询接口
            queryPrintData: async () => {
                const queryParams = ref({});
                const uniqueIds = ref<Array<any>>([]);
                const selectDatas = $table.getCheckboxRecords(true);
                XEUtils.arrayEach(selectDatas, (item) => {
                    uniqueIds.value.push(XEUtils.get(item, tableProps.uniqueId as string));
                });
                queryParams.value[tableProps.uniqueId] = uniqueIds.value.join(",");
                // 查询打印数据之前处理函数
                toolbarConfig.printDesign["printDataQueryBefore"] && typeof toolbarConfig.printDesign["printDataQueryBefore"] === "function" && toolbarConfig.printDesign["printDataQueryBefore"]({ queryParams, selectDatas, uniqueIds, $table });
                return queryBusinessData(queryParams.value).then((response: any) => {
                    if (toolbarConfig.printDesign["printDataQueryAfter"]) {
                        typeof toolbarConfig.printDesign["printDataQueryAfter"] != "function" && typeof toolbarConfig.printDesign["printDataQueryAfter"] === "string" && (toolbarConfig.printDesign["printDataQueryAfter"] = generateBaseFunc(toolbarConfig.printDesign["printDataQueryAfter"])) && toolbarConfig.printDesign["printDataQueryAfter"](response, $table, queryParams, selectDatas);
                    } else {
                        return response;
                    }
                });
            },
        };
        toolbarConfig.printDesign.previewPrintConfig = Object.assign({ ...toolbarConfig.printDesign?.previewPrintConfig }, preview);
    }
    // 直接打印
    if (toolbarConfig?.printDesign?.directPrint) {
        const direct = {
            queryPanel: () => {
                return callGetOne(toolbarConfig.printDesign?.directPrintConfig?.queryPanel).then((response: any) => {
                    return { data: JSON.parse(response.data?.panelData) };
                });
            },
            // 打印数据查询接口
            queryPrintData: async () => {
                const queryParams = ref({});
                const uniqueIds = ref<Array<any>>([]);
                const selectDatas = $table.getCheckboxRecords(true);
                XEUtils.arrayEach(selectDatas, (item) => {
                    uniqueIds.value.push(XEUtils.get(item, tableProps.uniqueId as string));
                });
                queryParams.value[tableProps.uniqueId] = uniqueIds.value.join(",");
                // 查询打印数据之前处理函数
                toolbarConfig.printDesign["printDataQueryBefore"] && typeof toolbarConfig.printDesign["printDataQueryBefore"] === "function" && toolbarConfig.printDesign["printDataQueryBefore"]({ queryParams, selectDatas, uniqueIds, $table });
                return queryBusinessData(queryParams.value).then((response: any) => {
                    if (toolbarConfig.printDesign["printDataQueryAfter"]) {
                        typeof toolbarConfig.printDesign["printDataQueryAfter"] != "function" && typeof toolbarConfig.printDesign["printDataQueryAfter"] === "string" && (toolbarConfig.printDesign["printDataQueryAfter"] = generateBaseFunc(toolbarConfig.printDesign["printDataQueryAfter"])) && toolbarConfig.printDesign["printDataQueryAfter"](response, $table, queryParams, selectDatas);
                    } else {
                        return response;
                    }
                });
            },
        };
        toolbarConfig.printDesign.directPrintConfig = Object.assign({ ...toolbarConfig.printDesign?.directPrintConfig }, direct);
    }
    // 打印公共接口
    if (toolbarConfig?.printDesign?.printApi) {
        const printApiDef = {
            queryPanel: () => {
                return callGetOne(toolbarConfig.printDesign?.printApi?.queryPanel).then((response) => {
                    return { data: JSON.parse(response.data?.panelData) };
                });
            },
            // 打印数据查询接口
            queryPrintData: async () => {
                const queryParams = ref({});
                const uniqueIds = ref<Array<any>>([]);
                const selectDatas = $table.getCheckboxRecords(true);
                XEUtils.arrayEach(selectDatas, (item) => {
                    uniqueIds.value.push(XEUtils.get(item, tableProps.uniqueId as string));
                });
                queryParams.value[tableProps.uniqueId] = uniqueIds.value.join(",");
                // 查询打印数据之前处理函数
                toolbarConfig.printDesign["printDataQueryBefore"] && typeof toolbarConfig.printDesign["printDataQueryBefore"] === "function" && toolbarConfig.printDesign["printDataQueryBefore"]({ queryParams, selectDatas, uniqueIds, $table });
                return queryBusinessData(queryParams.value).then((response: any) => {
                    if (toolbarConfig.printDesign["printDataQueryAfter"]) {
                        typeof toolbarConfig.printDesign["printDataQueryAfter"] != "function" && typeof toolbarConfig.printDesign["printDataQueryAfter"] === "string" && (toolbarConfig.printDesign["printDataQueryAfter"] = generateBaseFunc(toolbarConfig.printDesign["printDataQueryAfter"])) && toolbarConfig.printDesign["printDataQueryAfter"](response, $table, queryParams, selectDatas);
                    } else {
                        return response;
                    }
                });
            },
        };
        toolbarConfig.printDesign.directPrintConfig = printApiDef;
    }
    return toolbarConfig;
}
export function userPageConfig(pagerConfig: any) {
    return {
        ...pagerConfig,
        pageSizes: pagerConfig.pageSizes ? pagerConfig.pageSizes.split(",").map(Number) : [5, 10, 15, 20, 50, 100, 200, 500, 1000],
        layouts: pagerConfig.layouts ? pagerConfig.layouts.split(",") : ["PrevJump", "PrevPage", "Jump", "PageCount", "NextPage", "NextJump", "Sizes", "Total"],
    };
}
// 查询配置
export function userFormConfig(formConfig: VxeGridPropTypes.FormConfig) {
    const itemList = ref<Array<any>>([]);
    if (formConfig.items) {
        XEUtils.arrayEach(formConfig.items, (arrayItem: any) => {
            arrayItem = jsonFormat(arrayItem);
            itemList.value.push(arrayItem);
        });
    }
    formConfig.items = itemList.value.sort(function (prev: any, curr: any) {
        return prev.sortNo - curr.sortNo;
    });
    return formConfig;
}

/**
 * 处理表格配置
 * @param tableProps
 */
export function loadTable(tableProps: VxeBasicTable, $table: any) {
    if (tableProps["ext_params"]) {
        Object.assign(tableProps["params"], tableProps["extParams"]);
    }
    // 额外的参数配置
    if (tableProps["extra_config"]) {
        Object.assign(tableProps, tableProps["extraConfig"]);
    }
    // 处理字符串的boolean
    XEUtils.each(tableProps, (item, key) => {
        const v = stringToBoolean(item);
        if (typeof v === "boolean") {
            tableProps[key] = v;
        }
    });
    // 可编辑配置项
    if (tableProps["editConfig"] && tableProps["editConfig"]["beforeEditMethod"]) {
        tableProps["editConfig"]["beforeEditMethod"] = (data) => {
            const res = booleanFunction(tableProps["editConfig"]?.beforeEditMethod);
            if (typeof res === "boolean") {
                return res;
            } else {
                return res(data);
            }
        };
    }
    // 处理数据代理
    tableProps["proxyConfig"] = useProxyConfig(tableProps["proxyConfig"], tableProps["handConfig"], tableProps["uniqueId"], tableProps["formConfig"], tableProps["pagerConfig"]);
    // 表格列处理
    tableProps["columns"] = useColumns(tableProps["columns"]);
    // 工具栏配置
    tableProps["toolbarConfig"] = useToolBar(tableProps["toolbarConfig"], tableProps, $table);
    // 分页配置
    tableProps["pagerConfig"] = userPageConfig(tableProps["pagerConfig"]);
    // 查询配置
    // tableProps["formConfig"] = userFormConfig(tableProps["formConfig"]);
}
